# Copyright (c) 2007, Enrico Franchi
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of the University of California, Berkeley nor the
#       names of its contributors may be used to endorse or promote products
#       derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import threading
import Queue

class ConsciousThread(threading.Thread):
    def __init__(self, container, action):
        self.container = container
        self.action    = action
        super(ConsciousThread, self).__init__()
        
    def run(self):
        try:
            try:
                self.action.write_action
            except AttributeError:
                self.action()
            else:
                self.container.lock.acquire()
                self.action()
                self.container.lock.release()
        finally:
            self.container.removeThread(self)

class TaskExecutor(object):
    @classmethod
    def sharedExecutor(cls, **kargs):
        if not hasattr(cls, '_instance'):
            cls._instance = TaskExecutor(**kargs)
        return cls._instance 
    
    def __init__(self, queue=None):
        self.queue        = queue or Queue.Queue()
        self.threads      = []
        self.lock         = threading.RLock()
        self.tlock        = threading.RLock()
        self.t            = threading.Thread(target=self._consume)
        self.t.setDaemon(True)
        
    def run(self):
        self.t.start()
        
    def _consume(self):
        while True:
            action = self.queue.get()
            t = ConsciousThread(self, action)
            if hasattr(action, 'name'):
                t.setName(action.name)            
            self.addThread(t)
            t.start()

                
    def stop(self):
        self.t.stop()
            
    def addThread(self, thread):
        self.tlock.acquire()
        self.threads.append(thread)
        self.tlock.release()

    def removeThread(self, thread):
        self.tlock.acquire()
        self.threads.remove(thread)
        self.tlock.release()
        
    def addTask(self, task):
        self.queue.put(task)
        
    def __len__(self):
        return len(self.threads)
            
if __name__ == '__main__':
    q = Queue.Queue()
    te = TaskExecutor(queue=q)
    te.run()
    while True:
        s = raw_input('> ')
        if s.strip() == 'quit':
            print 'Quitting...'
            import os
            os.kill(os.getpid(), 15)
            
        class Say(object):
            def __init__(self, s):
                self.name = s
            def __call__(self): 
                import time
                print self.name, 'sleeping...'
                time.sleep(5)
                print self.name, 'finished.'
    
        te.addTask(Say(s))